package com.itheima.myiotest3;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;

public class Test1 {
    public static void main(String[] args) throws IOException {
        //获取本地文件学生信息并添加到集合中
        //由于这次学生信息有点多，可以创建学生类来封装学生信息
        ArrayList<Student> list=new ArrayList<>();
        BufferedReader br=new BufferedReader(new FileReader("myiotest\\src\\com\\itheima\\myiotest3\\test.txt"));
        String s;
        while((s=br.readLine())!=null){
            String[] split = s.split("-");
            Student stu=new Student(split[0],split[1],Integer.parseInt(split[2]),Double.parseDouble(split[3]));
            list.add(stu);
        }
        br.close();

        //计算学生权重占比
        //先求权重和
        double sum=0.0;
        for(int i=0;i<list.size();i++){
            sum+=list.get(i).getWeight();
        }
        //再求权重占比
        for (Student stu : list) {
            double v = stu.getWeight() / sum;
            stu.setWeight(v);
        }
        //更新本地文件权重信息
        BufferedWriter bw=new BufferedWriter(new FileWriter("myiotest\\test.txt"));
        for (Student stu : list) {
            bw.write(stu.toString());
            bw.newLine();
        }
        bw.close();

        //创建数组存抽取的概率分布
        double[] arr=new double[list.size()];
        arr[0]=list.get(0).getWeight();
        for(int i=0;i<arr.length-1;i++){
            arr[i+1]=list.get(i).getWeight()+arr[i];
        }

        //随机
        Double i=Math.random();
        System.out.println(i);
        //二分查找
        int index = -Arrays.binarySearch(arr, i)-1;
        System.out.println(index);//输出的是经过处理的i1，即抽取的学生下标
        System.out.println(list.get(index).getName());

        //抽到了的学生权重减一半
        double v = list.get(index).getWeight() / 2;
        list.get(index).setWeight(v);
        //更新本地文件权重信息
        BufferedWriter bw1=new BufferedWriter(new FileWriter("myiotest\\test.txt"));
        for (Student stu : list) {
            bw1.write(stu.toString());
            bw1.newLine();
        }
        bw1.close();


    }
}
